package com.pomelo.base.core.util;

import com.pomelo.base.core.bean.StreamCaptureThread;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;

/**
 * @Description: Shell 工具类
 * @Author: sunxin
 * @Param:
 * @Return:
 * @Date: 2021/10/16 9:38
 **/
public class ShellUtil {

    private static final Log LOGGER = LogFactory.getLog(ShellUtil.class);

    private ShellUtil() {

    }

    /**
     * @Description: 判断是否为windows系统
     * @Author: sunxin
     * @Param:
     * @Return:
     * @Date: 2021/10/16 9:37
     **/
    public static boolean isWindows() {
        return System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1;
    }

    /**
     * @Description: 模拟日志
     * @Author: sunxin
     * @Param:
     * @Return:
     * @Date: 2021/10/16 9:38
     **/
    private static int mockLog(String cmd) {
        LOGGER.debug("当前系统为windows, 模拟运行命令:" + cmd);
        return 0;
    }

    public static int execCmd(String cmd) {
        StringBuffer sb = new StringBuffer();
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            getProcessOutput(process, sb);
        } catch (Exception e) {
            if (sb != null) {
                sb.append("executeCmd: " + cmd + "\n");
                sb.append("errorMessage: " + e.toString() + "\n");
            }
        }
        int code = 0;
        if (process != null) {
            try {
                code = process.waitFor();
                process.getOutputStream().close();
                process.getErrorStream().close();
                process.getInputStream().close();
            } catch (InterruptedException e) {
                LOGGER.error(e);
            } catch (IOException e) {
                LOGGER.error(e);
            }
        }
        LOGGER.info(sb.toString());
        return code;
    }

    private static void getProcessOutput(Process process, StringBuffer sb) {
        if (process == null) {
            return;
        }
        StreamCaptureThread errorStream = new StreamCaptureThread(process.getErrorStream());
        StreamCaptureThread inputStream = new StreamCaptureThread(process.getInputStream());
        errorStream.setOutput(sb);
        inputStream.setOutput(sb);
        new Thread(errorStream).start();
        new Thread(inputStream).start();
    }

}
